#include "Socket.hpp"
#include <signal.h>
#include <functional>

using func_t = std::function<std::string(std::string &package)>;
const std::string serverip_ = "0.0.0.0";

class TcpServer
{

public:
    TcpServer(const uint16_t &port, func_t func)
        : port_(port), calculator_(func)
    {
    }

    void Init()
    {
        // 创建套接字 , 绑定 , 设置监听模式
        sock_.Init();
        sock_.Bind(serverip_, port_);
        sock_.Listen();
    }

    void Start()
    {
        signal(SIGCLD, SIG_IGN);
        while (true)
        {
            // 与客户端建立连接
            std::string clientip;
            uint16_t clientport;
            int sockfd = sock_.Accept(clientip, clientport);
            lg_(Info, "accept a connet , ip : %s , port : %d ", clientip.c_str(), clientport);

            // 接受服务端的请求
            std::string package;
            char buffer[1024];

            if (fork() == 0) // 创建子进程为与用户进行通信
            {
                while (true)
                {
                    int n = read(sockfd, buffer, sizeof(buffer));
                    if (n > 0)
                    {
                        buffer[n] = 0;
                        package += buffer;
                        // 对报文进行解包 + 反序列化 + 计算 + 构造response + 序列化 + 加报文
                        std::string ret_package = calculator_(package);


                        write(sockfd, ret_package.c_str(), ret_package.size());
                    }
                }
            }
        }
    }

private:
    Socket sock_;
    uint16_t port_;
    func_t calculator_;
};